package com.sansecy.mocklocationtest;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class getInstalledApps extends AsyncTask<Void, String, Void> {
    ArrayList<AppInfo> appList;
    ArrayList<AppInfo> appSystemList;
    ArrayList<AppInfo> appHiddenList;
    private Integer totalApps;
    private Integer actualApps;
    private OnCompleteListener<ArrayList<AppInfo>> mArrayListOnCompleteListener;

    public void setArrayListOnCompleteListener(OnCompleteListener<ArrayList<AppInfo>> arrayListOnCompleteListener) {
        mArrayListOnCompleteListener = arrayListOnCompleteListener;
    }

    public getInstalledApps() {
        actualApps = 0;

        appList = new ArrayList<>();
        appSystemList = new ArrayList<>();
        appHiddenList = new ArrayList<>();
    }

    @Override
    protected Void doInBackground(Void... params) {
        final PackageManager packageManager = App.getApp().getPackageManager();
        List<PackageInfo> packages = packageManager.getInstalledPackages(PackageManager.GET_META_DATA);
        totalApps = packages.size();
        // Get Sort Mode
        switch (App.getApp().getCustomFilename()) {
            default:
                // Comparator by Name (default)
                Collections.sort(packages, new Comparator<PackageInfo>() {
                    @Override
                    public int compare(PackageInfo p1, PackageInfo p2) {
                        return packageManager.getApplicationLabel(p1.applicationInfo).toString().toLowerCase().compareTo(packageManager.getApplicationLabel(p2.applicationInfo).toString().toLowerCase());
                    }
                });
                break;
            case "2":
                // Comparator by Size
                Collections.sort(packages, new Comparator<PackageInfo>() {
                    @Override
                    public int compare(PackageInfo p1, PackageInfo p2) {
                        Long size1 = new File(p1.applicationInfo.sourceDir).length();
                        Long size2 = new File(p2.applicationInfo.sourceDir).length();
                        return size2.compareTo(size1);
                    }
                });
                break;
            case "3":
                // Comparator by Installation Date (default)
                Collections.sort(packages, new Comparator<PackageInfo>() {
                    @Override
                    public int compare(PackageInfo p1, PackageInfo p2) {
                        return Long.toString(p2.firstInstallTime).compareTo(Long.toString(p1.firstInstallTime));
                    }
                });
                break;
            case "4":
                // Comparator by Last Update
                Collections.sort(packages, new Comparator<PackageInfo>() {
                    @Override
                    public int compare(PackageInfo p1, PackageInfo p2) {
                        return Long.toString(p2.lastUpdateTime).compareTo(Long.toString(p1.lastUpdateTime));
                    }
                });
                break;
        }

        // Installed & System Apps
        for (PackageInfo packageInfo : packages) {
            if (!(packageManager.getApplicationLabel(packageInfo.applicationInfo).equals("") || packageInfo.packageName.equals(""))) {

                if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                    try {
                        // Non System Apps
                        AppInfo tempApp = new AppInfo(packageManager.getApplicationLabel(packageInfo.applicationInfo).toString(), packageInfo.packageName, packageInfo.versionName,
                                packageInfo.applicationInfo.sourceDir, packageInfo.applicationInfo.dataDir, packageManager.getApplicationIcon(packageInfo.applicationInfo), false);
                        appList.add(tempApp);
                    } catch (OutOfMemoryError e) {
                        //TODO Workaround to avoid FC on some devices (OutOfMemoryError). Drawable should be cached before.
                        AppInfo tempApp = new AppInfo(packageManager.getApplicationLabel(packageInfo.applicationInfo).toString(), packageInfo.packageName, packageInfo.versionName, packageInfo.applicationInfo.sourceDir, packageInfo.applicationInfo.dataDir, new BitmapDrawable(), false);
                        appList.add(tempApp);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        // System Apps
                        AppInfo tempApp = new AppInfo(packageManager.getApplicationLabel(packageInfo.applicationInfo).toString(), packageInfo.packageName, packageInfo.versionName, packageInfo.applicationInfo.sourceDir, packageInfo.applicationInfo.dataDir, packageManager.getApplicationIcon(packageInfo.applicationInfo), true);
                        appSystemList.add(tempApp);
                    } catch (OutOfMemoryError e) {
                        //TODO Workaround to avoid FC on some devices (OutOfMemoryError). Drawable should be cached before.
                        AppInfo tempApp = new AppInfo(packageManager.getApplicationLabel(packageInfo.applicationInfo).toString(), packageInfo.packageName, packageInfo.versionName, packageInfo.applicationInfo.sourceDir, packageInfo.applicationInfo.dataDir, new BitmapDrawable(), false);
                        appSystemList.add(tempApp);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            actualApps++;
            publishProgress(Double.toString((actualApps * 100) / totalApps));
        }

//        // Hidden Apps
//        for (String app : hiddenApps) {
//            AppInfo tempApp = new AppInfo(app);
//            Drawable tempAppIcon = UtilsApp.getIconFromCache(context, tempApp);
//            tempApp.setIcon(tempAppIcon);
//            appHiddenList.add(tempApp);
//
//            actualApps++;
//            publishProgress(Double.toString((actualApps * 100) / totalApps));
//        }

        return null;
    }

    @Override
    protected void onProgressUpdate(String... progress) {
        super.onProgressUpdate(progress);
//        progressWheel.setProgress(Float.parseFloat(progress[0]));
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        if (mArrayListOnCompleteListener != null) {
            mArrayListOnCompleteListener.onComplete(appList);
        }
    }

    public interface OnCompleteListener<T> {
        void onComplete(T t);
    }

}